package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.PageResult;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.utils.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }


    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 根据ID删除品牌数据(逻辑删除)
     * @param spuId
     */
    @Override
    public void delete(String spuId){
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品不存在!");
        }
        //必须先下架商品才能够删除
        String status = "0";
        if (!status.equals(spu.getIsMarketable())){
            throw new RuntimeException("该商品目前还在售中,无法删除");
        }
        //删除状态: 1代表逻辑删除
        spu.setIsDelete("1");
        //初始化审核状态:0代表未审核
        spu.setStatus(status);
        //同步spu和其对应的sku的商品的状态
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", spu.getId());
        List<Sku> skuList = skuMapper.selectByExample(example);
        if (skuList!=null||skuList.size()>0){
            for (Sku sku : skuList) {
                sku.setStatus(status);
                skuMapper.updateByPrimaryKeySelective(sku);
            }
        }
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Goods> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        List<Spu> spuList = spuMapper.selectByExample(example);
        List<Goods> goodsList = new ArrayList<Goods>();
        if (spuList!=null&&spuList.size()>0){
            for (Spu spu : spuList) {
                Example example1 = new Example(Sku.class);
                example1.createCriteria()
                        .andEqualTo("spuId", spu.getId())
                        .andEqualTo("status",spu.getStatus());
                List<Sku> skuList = skuMapper.selectByExample(example1);
                goodsList.add(new Goods(spu,skuList));
            }
        }
        return goodsList;
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<Goods> findPage(int page, int size){
        PageHelper.startPage(page,size);
        Page<Spu> spuPage = (Page<Spu>) spuMapper.selectAll();
        List<Spu> spuList = spuPage.getResult();
        List<Goods> goodsList = new ArrayList<Goods>();
        if (spuList!=null&&spuList.size()>0){
            for (Spu spu : spuList) {
                Example example = new Example(Sku.class);
                example.createCriteria()
                        .andEqualTo("spuId", spu.getId())
                        .andEqualTo("status",spu.getStatus());
                List<Sku> skuList = skuMapper.selectByExample(example);
                goodsList.add(new Goods(spu,skuList));
            }
        }
        return new PageResult<Goods>(spuPage.getTotal(),goodsList);
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageResult<Goods> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Spu> spuPage = (Page<Spu>) spuMapper.selectByExample(example);
        List<Spu> spuList = spuPage.getResult();
        ArrayList<Goods> goodsList = new ArrayList<>();
        if (spuList!=null&&spuList.size()>0){
            for (Spu spu : spuList) {
                Example example1 = new Example(Sku.class);
                example1.createCriteria()
                        .andEqualTo("spuId", spu.getId())
                        .andEqualTo("status",spu.getStatus());
                List<Sku> skuList = skuMapper.selectByExample(example1);
                goodsList.add(new Goods(spu,skuList));
            }
        }
        return new PageResult<Goods>(spuPage.getTotal(),goodsList);
    }

    /**
     * 商品上架
     * @param spuId 商品spuId
     */
    @Override
    public void pushSpu(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品不存在!");
        }
        //只要不是过审状态都不能上架
        if (!"1".equals(spu.getStatus())){
            throw new RuntimeException("该商品还未审核!");
        }
        //删除后的商品不能上架
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品已被删除!");
        }
        //设置上架信息为:1代表上架
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品下架
     * @param spuId 商品spuId
     */
    @Override
    public void pullSpu(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品不存在!");
        }
        //若商品已被删除,则不能进行下架操作
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品还未上架!");
        }
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /***
     * 根据ID删除品牌数据(完全删除,从回收站删除)
     * @param spuId 商品id
     */
    @Override
    public void realDel(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品已被删除");
        }
        //物理删除的前提为必须先逻辑删除该商品
        if (!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品还未被移入回收站(或已被还原)");
        }
        spuMapper.delete(spu);
    }

    /**
     * 根据ID查询商品数据
     * @param spuId 商品spuId
     * @return Goods
     */
    @Override
    public Goods findGoodsById(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品不存在!");
        }
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spuId);
        List<Sku> skuList = skuMapper.selectByExample(example);
        Goods goods = new Goods(spu,skuList);
        return goods;
    }

    /***
     * 修改商品数据
     * @param goods 包含spu以及skuList的goods
     */
    @Override
    public void update(Goods goods) {
        //非空校验
        if (goods==null){
            throw new RuntimeException("无效的数据!");
        }
        Spu spu = goods.getSpu();
        if (spu==null){
            return;
        }
        //先修改spu
        spuMapper.updateByPrimaryKeySelective(spu);
        //将sku表中spuId对应此spu的数据先删除掉
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",spu.getId());
        skuMapper.deleteByExample(example);
        this.saveSkuList(goods);
    }

    /***
     * 从回收站还原商品
     * @param spuId
     */
    @Override
    public void restore(String spuId) {
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        //非空校验
        if (spu==null){
            throw new RuntimeException("该商品不存在!");
        }
        //只有被逻辑删除的商品才能被还原
        if (!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品处于非法状态");
        }
        //是否被删除: 0-->未删除
        spu.setIsDelete("0");
        //初始化该商品的状态
        spu.setStatus("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 根据传入的goods向sku表中添加数据
     * @param goods
     */
    private void saveSkuList(Goods goods) {
        //首先确保skuList不为空，若skuList为空，直接结束方法，节省内存，提高效率
        List<Sku> skuList = goods.getSkuList();
        if (skuList==null||skuList.size()<=0){
            return;
        }
        //准备好数据,封装之后,添加到数据库中
        Spu spu = goods.getSpu();
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        //检验这个品牌和分类有没有关联关系,若没有关联关系,则添加此关联关系
        CategoryBrand categoryBrand = new CategoryBrand(category.getId(), brand.getId());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count<=0){
            categoryBrandMapper.insertSelective(categoryBrand);
        }
        //循环封装数据,并添加到数据库表中
        for (Sku sku : skuList) {
            //skuId
            sku.setId(idWorker.nextId()+"");
            //spuId
            sku.setSpuId(spu.getId());
            //spec
            if (StringUtils.isEmpty(sku.getSpec())){
                sku.setSpec("{}");
            }
            //日期
            Date date = new Date();
            sku.setCreateTime(date);
            sku.setUpdateTime(date);
            //name
            StringBuilder originalName = new StringBuilder(spu.getName());
            Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            if (specMap!=null&&specMap.size()>0){
                for (String value : specMap.values()) {
                    originalName.append(" ").append(value);
                }
            }
            //category
            sku.setCategoryId(category.getId());
            sku.setCategoryName(category.getName());
            //brand
            sku.setBrandName(brand.getName());
            skuMapper.insertSelective(sku);
        }
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
